import { Card } from '../card/base/Card';
import { logger } from '../utils/logger';
import { Room } from './Room';

export namespace CardEvent {
	/**
	 * 添加到手牌
	 * @param room
	 * @param user
	 * @param card
	 * @returns
	 */
	export function addCard(room: Room, user: string, card: Card) {
		const dept = room.getDept(user);
		if (!dept || !card) return;
		// 获得事件
		card.give(room, user);
		// 添加手牌
		dept.handCards.push(card);
		// 播放日志
		logger.info(`AddCard ${card.cardId}`);
	}

	/**
	 * 破坏场上卡牌
	 * @param room
	 * @param deptId
	 * @param index
	 * @returns
	 */
	export function destroyFieldCard(room: Room, deptId: string, index: number) {
		const dept = room.getDept(deptId);
		if (!dept) return;
		const card = dept.fieldCards[index];
		if (!card) return;
		card.destroy(room, deptId);
		room.pools.back(card);
		dept.fieldCards.splice(index, 1);
	}

	/**
	 * 破坏手牌卡牌
	 * @param room
	 * @param deptId
	 * @param index
	 * @returns
	 */
	export function destroyHandCard(room: Room, deptId: string, index: number) {
		const dept = room.getDept(deptId);
		if (!dept) return;
		const card = dept.handCards[index];
		if (!card) return;
		card.destroy(room, deptId);
		room.pools.back(card);
		dept.handCards.splice(index, 1);
	}

	/**
	 * 抽牌
	 * @param room
	 * @param deptId
	 * @param count
	 */
	export function drawCard(
		room: Room,
		deptId: string,
		pool: string,
		count: number,
		global: boolean = true
	) {
		for (let i = 0; i < count; i++) {
			const card = room.pools.draw(pool, global);
			if (card) CardEvent.addCard(room, deptId, card);
		}
	}

	/**
	 * 使用卡牌
	 * @param room
	 * @param deptId
	 * @param index
	 * @param target
	 * @returns
	 */
	export function useCard(
		room: Room,
		deptId: string,
		index: number,
		target: string,
	) {
		const dept = room.getDept(deptId);
		if (!dept) return;
		const card = dept.handCards[index];
		if (!card) return;
		const costPoint = card.costPoint(room, deptId);
		const costMoney = card.costMoney(room, deptId);
		if (
			dept.point >= costPoint &&
			dept.getDeptDataValue('money') >= costMoney
		) {
			// 扣除花费
			dept.point -= costPoint;
			dept.addDeptDataValue('money', -costMoney);
			// 使用效果
			card.use(room, dept.deptId, target);
			// 是否上场
			if (card.canToField(room, deptId)) dept.fieldCards.push(card);
			CardEvent.destroyHandCard(room, deptId, index);
			// 发送消息
			room.send('message', `${dept.name} 打出 ${card.title(room, deptId)}`);
		}
	}
}
